import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, GuardsCheckEnd, NavigationCancel, NavigationEnd, Router} from '@angular/router';
import {FormBuilder, FormGroup} from '@angular/forms';
import {Observable, of} from 'rxjs';
import {filter} from 'rxjs/operators';

@Component({
  selector: 'app-order-edit',
  templateUrl: './order-edit.component.html',
  styleUrls: ['./order-edit.component.less']
})
export class OrderEditComponent implements OnInit {
  form: FormGroup;
  info = {};

  constructor(
    private fb: FormBuilder,
    private activatedRoute: ActivatedRoute,
    private router: Router) {
    router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((event: NavigationEnd) => {
      console.log('NavigationEnd', router);
      console.log('NavigationEnd', event);
    });
    router.events.pipe(filter(event => event instanceof NavigationCancel)).subscribe((event: NavigationCancel) => {
      const index = window.location.hash.indexOf('?');
      if (index !== -1) {
        window.location.hash = window.location.hash.substr(0, index);
      }
    });
    router.events.pipe(filter(event => event instanceof GuardsCheckEnd)).subscribe((event: GuardsCheckEnd) => {
      console.log('GuardsCheckEnd', router);
      console.log('GuardsCheckEnd', event);
    });
  }

  toUpdateComponent() {
    this.router.navigate(['/orders/order-edit'], {
      skipLocationChange: true,
      queryParams: {
        info: JSON.stringify(this.info),
        random: Math.random()
      }
    });
  }

  ngOnInit() {
    this.initForm();
    this.initInfo();
  }
  /*
   * 初始化业务信息*/
  initInfo() {
    this.activatedRoute.queryParams.subscribe(data => {
      if (data && data['info']) {
        this.info = JSON.parse(data['info']);
        /*const formModel = this.form.value;
        Object.keys({formModel}).forEach( key => {
          formModel[key] = typeof this.info[key] !== 'undefined' ? null : this.info[key];
        });*/
        this.form.setValue(this.info);
      }
    });
  }

  /*
   * 初始化响应式表单*/
  initForm() {
    if (!this.form) {
      this.form = this.fb.group({
        name: [null],
        age: [null]
      });
    }
  }

  canDeactivate(): Observable<boolean>|boolean {
    if (!this.form.dirty) {
      return true;
    }
    return of(confirm('表单信息修改后未保存，确定离开吗？'));
  }

}
